#
# Ronin Exploits - A Ruby library for Ronin that provides exploitation and
# payload crafting functionality.
#
# Copyright (c) 2007-2013 Hal Brodigan (postmodern.mod3 at gmail.com)
#
# This file is part of Ronin Exploits.
#
# Ronin is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ronin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ronin.  If not, see <http://www.gnu.org/licenses/>
#

require 'ronin/exploits/remote_tcp'
require 'ronin/network/mixins/http'

require 'uri/query_params'

module Ronin
  module Exploits
    #
    # An {Exploit} class that represents exploits against HTTP servers.
    #
    class HTTP < RemoteTCP

      # Default port to connect to
      DEFAULT_PORT = 80

      include Network::Mixins::HTTP

      # The optional URL path prefix
      parameter :url_prefix, type:        String,
                             description: 'Optional URL path prefix'

      #
      # Constructs a URL for the given path.
      #
      # @param [String] path
      #   The path for the new URL.
      #
      # @param [Hash] query_params
      #   Additional query parameters for the URL.
      #
      # @return [URI::HTTP]
      #   The new URL.
      #
      # @example
      #   url_for '/path'
      #   # => #<URI::HTTP:0x00000000cf53a0 URL:http://example.com/path>
      #
      # @example with a query-string
      #   url_for '/path?q=1'
      #   # => #<URI::HTTP:0x00000000cf53a0 URL:http://example.com/path?q=1>
      #
      # @example with query-params.
      #   url_for '/path', q: 1
      #   # => #<URI::HTTP:0x00000000cf53a0 URL:http://example.com/path?q=1>
      #
      def url_for(path,query_params={})
        require_params :host

        path, query = path.split('?',2)

        url = ::URI::HTTP.build(
          host:  self.host,
          port:  self.port,
          path:  path,
          query: query
        )

        if self.url_prefix
          # add tue url prefix
          url.path = File.join('',self.url_prefix,url.path)
        end

        # add additional query params
        url.query_params.merge!(query_params)

        return url
      end

    end
  end
end
